package cn.tedu.msfrsp.ex.handler;


import cn.tedu.msfrsp.ex.ServiceException;
import cn.tedu.msfrsp.web.JsonResult;
import cn.tedu.msfrsp.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 全局异常处理器
 *
 * @author wcl
 * @version 0.0.1
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler(){
        log.debug("创建全局异常处理对象:GlobalExceptionHandler");
    }

    /**
     * 处理 ServiceException 异常
     * @param e ServiceException异常
     * @return 对应的状态码和异常信息
     */
    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ServiceException e){
        log.debug("处理请求的方法时抛出了ServiceException,将统一处理");
        return JsonResult.fail(e);
    }

    /**
     * 处理检查添加管理员参数的异常
     * @param e BindException异常
     * @return 对应的响应码和异常信息
     */
    @ExceptionHandler
    public JsonResult<Void> handleBindException(BindException e){
        log.debug("开始处理BindException");

        String defaultMessage = e.getFieldError().getDefaultMessage();

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,defaultMessage);
    }

    /**
     * 处理检查根据id删除管理员参数的异常
     * @param e ConstraintViolationException 异常
     * @return 对应的响应码和异常信息
     */
    @ExceptionHandler
    public JsonResult<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.debug("开始处理ConstraintViolationException");
        StringJoiner stringJoiner = new StringJoiner("，");
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            stringJoiner.add(constraintViolation.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, stringJoiner.toString());
    }

    @ExceptionHandler
    public JsonResult<Void> handleAccessDeniedException(AccessDeniedException e) {
        log.debug("AccessDeniedException");
        String message = "您登录的角色没有权限访问！";
        return JsonResult.fail(ServiceCode.ERR_FORBIDDEN, message);
    }

    @ExceptionHandler
    public String handleThrowable(Throwable e) {
        String message = "您有异常没有处理,请根据服务器控制台的信息来处理相关的异常";
        e.printStackTrace();
        return message;
    }
}
